package com.example.app;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.example.app.Websocket.APP;
import com.example.app.Websocket.StaticData;
import com.example.app.Websocket.AppDatabase;
import com.example.app.Entity.Friend;
import com.example.app.Entity.FriendEntity;
import com.example.app.Entity.FriendStatus;
import com.example.app.Entity.User;
import com.example.app.Entity.UserEntity;
import com.example.app.Entity.UserRole;
import com.google.gson.Gson;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.UUID;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class LoginActivity extends AppCompatActivity {
    private EditText editTextUsername;
    private EditText editTextPassword;
    String  nickname;
    String  Email;
    String  role;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.loginpage);
        editTextUsername = findViewById(R.id.editTextUsername);
        editTextPassword = findViewById(R.id.editTextPassword);
        Button buttonLogin = findViewById(R.id.buttonLogin);
        buttonLogin.setOnClickListener(v -> {
            String username = editTextUsername.getText().toString();
            String password = editTextPassword.getText().toString();
            loginUser(username, password);
        });

        SharedPreferences prefs = getSharedPreferences("user_credentials", MODE_PRIVATE);
        String username = prefs.getString("username", "");
        String password=prefs.getString("password","");
        if (!username.isEmpty() && !password.isEmpty()){
            APP.initWebRTCManager(getApplicationContext(), username);
            startActivity(new Intent(LoginActivity.this, MainActivity.class));
        }


    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
    private void loginUser(String username, String password) {
        RadioGroup radioGroup = findViewById(R.id.radioGroupRole);
        int selectedId = radioGroup.getCheckedRadioButtonId();
        role = (selectedId == R.id.radioUser) ? "user" : "doctor";
        System.out.println("------------------------------"+role+"角色------------------------------------");
        @SuppressLint("HardwareIds") String deviceId = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
        System.out.println("设备id："+deviceId);
        if (TextUtils.isEmpty(deviceId)) {
            deviceId = UUID.randomUUID().toString();
        }
        String url = "https://" + StaticData.WebSocketHOSTS + "/Login";
        String finalDeviceId = deviceId;
        @SuppressLint("StaticFieldLeak") AsyncTask<String, Void, String> task = new AsyncTask<String, Void, String>() {
            @Override
            protected String doInBackground(String... params) {
                try {
                    @SuppressLint("CustomX509TrustManager") TrustManager[] trustAllCerts = new TrustManager[]{
                            new X509TrustManager() {
                                @SuppressLint("TrustAllX509TrustManager")
                                public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
                                @SuppressLint("TrustAllX509TrustManager")
                                public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
                                public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; }
                            }
                    };
                    SSLContext sslContext = SSLContext.getInstance("TLS");
                    sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
                    HttpsURLConnection urlConnection = getHttpsURLConnection(params, sslContext);
                    try (OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream())) {
                        String requestBody = String.format(
                                "{\"username\":\"%s\",\"password\":\"%s\",\"deviceId\":\"%s\",\"Role\":\"%s\"}",
                                params[0], params[1], finalDeviceId,role
                        );
                        out.write(requestBody.getBytes(StandardCharsets.UTF_8));
                    }
                    int statusCode = urlConnection.getResponseCode();
                    if (statusCode == 200) {
                        InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                        StringBuilder response = new StringBuilder();
                        String line;
                        while ((line = reader.readLine()) != null) {
                            response.append(line);
                        }
                        JSONObject jsonObject = new JSONObject(response.toString());
                        Gson gson = new Gson();
                        JSONObject userJson = jsonObject.getJSONObject("user");
                        User user = gson.fromJson(userJson.toString(), User.class);
                        JSONArray friendsArray = jsonObject.getJSONArray("friends");
                        String accessToken = jsonObject.getString("accessToken");
                        String refreshToken = jsonObject.getString("refreshToken");
                        System.out.println("accessToken========="+accessToken);
                        System.out.println("refreshToken========="+refreshToken);
                        User currentUser = gson.fromJson(userJson.toString(), User.class);
                        List<Friend> friends = parseFriends(friendsArray);
                        AppDatabase db = AppDatabase.getInstance(LoginActivity.this);
                        db.runInTransaction(() -> {
                            UserEntity currentUserEntity = convertToUserEntity(currentUser);
                            db.userDao().insert(currentUserEntity);
                            db.friendDao().deleteByUserId(currentUser.getUserId());
                            for (Friend friend : friends) {
                                User friendUser = friend.getFriend();
                                UserEntity friendEntity = convertToUserEntity(friendUser);
                                db.userDao().insert(friendEntity);
                                FriendEntity friendRelation = new FriendEntity();
                                friendRelation.setUserId(currentUser.getUserId());
                                friendRelation.setFriendUserId(friendUser.getUserId());
                                friendRelation.setRemark(friend.getRemark());
                                friendRelation.setCategory(friend.getCategory());
                                friendRelation.setStatus(friend.getStatus());
                                db.friendDao().insert(friendRelation);
                            }
                        });
                        SharedPreferences sharedPreferences = getSharedPreferences("user_credentials", Context.MODE_PRIVATE);
                        sharedPreferences.edit().putString("current_user_id", currentUser.getUserId()).apply();
                        SharedPreferences.Editor editor = sharedPreferences.edit();
                        System.out.println("\n\n\n\n\n"+userJson.get("userId")+"\n\n\n\n");
                        editor.putString("accessToken", accessToken);
                        editor.putString("refreshToken", refreshToken);
                        editor.putString("deviceId", finalDeviceId); // 保存设备ID
                        nickname=user.getNickname();
                        Email=user.getEmail();
                        editor.apply();
                        return "登录成功";
                    }
                    System.out.println("返回码："+statusCode);
                    if (statusCode==403){
                        return "用户名，角色或密码错误，请重新输入";
                    }else {
                        return "服务器错误";
                    }
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                    return "错误"+e.getMessage();
                }
            }
            private UserEntity convertToUserEntity(User user) {
                UserEntity entity = new UserEntity();
                entity.setUserId(user.getUserId());
                entity.setEmail(user.getEmail());
                entity.setNickname(user.getNickname());
                entity.setAvatarUrl(user.getAvatarUrl());
                entity.setRole(user.getRole());
                return entity;
            }
            @Override
            protected void onPostExecute(String result) {
                Toast.makeText(LoginActivity.this, result, Toast.LENGTH_SHORT).show();
                if (result.equals("登录成功")) {
                    saveCredentials();
                    SharedPreferences prefs = getSharedPreferences("user_credentials", MODE_PRIVATE);
                    String username = prefs.getString("username", "");
                    APP.initWebRTCManager(getApplicationContext(), username);
                    APP.initializeDataWebSocket(getApplicationContext(),username);
                    startActivity(new Intent(LoginActivity.this, MainActivity.class));
                    finish();
                }
            }
            private void saveCredentials() {
                SharedPreferences prefs = getSharedPreferences("user_credentials", Context.MODE_PRIVATE);
                prefs.edit()
                        .putString("username", username)
                        .putString("password", password)
                        .putString("nickname",nickname)
                        .putString("Email",Email)
                        .putString("Role",role)
                        .apply();
                System.out.println(prefs.getString("nickname","出错了"));
            }
        };
        task.execute(username, password, url);
    }
    @NonNull
    private static HttpsURLConnection getHttpsURLConnection(String[] params, SSLContext sslContext) throws IOException {
        URL url = new URL(params[2]);
        HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
        urlConnection.setSSLSocketFactory(sslContext.getSocketFactory());
        urlConnection.setHostnameVerifier((hostname, session) -> true);
        urlConnection.setRequestMethod("POST");
        urlConnection.setRequestProperty("Content-Type", "application/json");
        urlConnection.setDoOutput(true);
        return urlConnection;
    }
    private List<Friend> parseFriends(JSONArray friendsArray) throws JSONException {
        List<Friend> friends = new ArrayList<>();
        if (friendsArray == null) return friends;
        Gson gson = new Gson();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.getDefault());
        try {
            for (int i = 0; i < friendsArray.length(); i++) {
                JSONObject friendJson = friendsArray.getJSONObject(i);
                System.out.println(friendJson);
                long id = friendJson.optLong("id", -1L);
                String category = friendJson.optString("category", "默认分组");
                String remark = friendJson.optString("remark", "");
                FriendStatus status;
                try {
                    status = FriendStatus.valueOf(friendJson.getString("status"));
                } catch (Exception e) {
                    status = FriendStatus.PENDING; // 默认值
                    Log.w("Parse", "Invalid friend status, using default", e);
                }
                JSONObject friendUserJson = friendJson.optJSONObject("friend");
                if (friendUserJson == null) {
                    Log.w("Parse", "Missing friend user data, skipping item");
                    continue;
                }
                User friendUser = new User();
                friendUser.setId(friendUserJson.optLong("id"));
                friendUser.setEmail(friendUserJson.optString("email"));
                friendUser.setUserId(friendUserJson.optString("userId"));
                friendUser.setNickname(friendUserJson.optString("nickname"));
                try {
                    UserRole role = UserRole.valueOf(friendUserJson.getString("role"));
                    friendUser.setRole(role);
                } catch (Exception e) {
                    friendUser.setRole(UserRole.USER); // 默认角色
                    Log.w("Parse", "Invalid user role, using default", e);
                }
                Friend friend = new Friend();
                friend.setId(id);
                friend.setStatus(status);
                friend.setCategory(category);
                friend.setRemark(remark);
                friend.setFriend(friendUser);
                if (friendJson.has("createdAt")) {
                    try {
                        Date createdAt = dateFormat.parse(friendJson.getString("createdAt"));
                    } catch (Exception e) {
                        Log.w("Parse", "Failed to parse date", e);
                    }
                }
                friends.add(friend);
            }
        } catch (JSONException e) {
            Log.e("Parse", "Failed to parse friends data", e);
        }
        return friends;
    }
}